define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/stats/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        cst = require('js/frame/const'),
        app = Backbone.history;

    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var GameOrderListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch'
        },
        initialize: function (options) {
            this.options = options;
            if(null == options.user_id){
                options.user_id = 0;
            }
            this.collection = new models.AccountTransactionCollection(options);
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },

        _getSearchOption: function () {
            delete this.options.title;
            var options = {};
            var searched = utils.getAllInput('#sidebar_right');
            searched.user_id = parseInt($('#searchUserID').val());
            searched.selectedType = parseInt($('#searchType').val());
            searched.created_at_lower = $("#searchCreatedAtLower").val();
            searched.created_at_upper = $('#searchCreatedAtUpper').val();
            searched.title = $("#searchTitle").val();
            if(searched.title && searched.title.length > 0) {
                options.title = JSON.stringify({ '$in': searched.title });
            }
            if (searched.created_at_lower || searched.created_at_upper) {
                options.created_at = {};
                if (searched.created_at_lower) options.created_at.$gte = searched.created_at_lower;
                if (searched.created_at_upper) options.created_at.$lt = searched.created_at_upper;
            }
            if (!isNaN(searched.user_id)) {
                options.user_id = searched.user_id;
            }
            if(searched.selectedType) {
                if (searched.selectedType > 0) {
                    options.price = JSON.stringify({'$gte': 0});
                }
                else {
                    options.price = JSON.stringify({'$lte': 0});
                }
            }
            else
                delete options.price;
            utils.saveSearched('op/transaction/', searched);
            return options;
        },

        doSearch: function () {
            var options = this._getSearchOption();
            options.$page = 1;
            options.$size = 30;
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/transaction/', options), {
                trigger: true
            });
        },

        renderWithData: function () {
            _.each(this.collection.models, function(data) {
                if(data.attributes.extend){
                    var extend = JSON.parse(data.attributes.extend);
                    if(extend.hasOwnProperty('coupon_price')){
                        data.attributes.price = parseInt(data.attributes.price) - parseInt(extend.coupon_price);
                        data.attributes.coupon = extend.coupon_price;
                    }
                }
            });
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                total_income: this.collection.total_income,
                total_outcome: this.collection.total_outcome,
                searched: utils.getSearched('op/transaction/')
            }));
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/transaction/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            utils.multiselect('#searchTitle', true, {
                'includeSelectAllOption': true
            });
            $('[data-type=date]').datetimepicker({
                defaultDate: false,
                format: 'YYYY-MM-DD HH:mm:ss'
            });


            $('.modify-item').magnificPopup({
                items: {
                    src: '#editWithdrawPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {

                        $('#order_id').text("");
                        $('#user_id').text("");
                        $('#activity_type').text("");
                        $('#bet_name').text("");
                        $('#term').text("");
                        $('#number').text("");
                        $('#price').text("");
                        $('#win_price').text("");
                        $('#bonus').text("");
                        $('#orderStatus').text("");
                        $('#created_at').text("");
                        $('#updated_at').text("");

                        $('#riskInfo').html('');
                        var data_id = $(this.st.el).closest('tr').data('id'),
                            choosen = that.collection.get(data_id);
                        var title = choosen.get('title');
                        var activity_type = choosen.get('activity_type');
                        var order_id = choosen.get('order_id');
                        var game = "";
                        if("参与水果机" == title){
                            game = "fruit";
                        }else if("参与牛牛" == title){
                            game = "bull";
                        }else if("参与slots" == title){
                            game = "kfc";
                        }
                        if(null == game || "" == game){
                            $.get('/admin/order/?order_id='+order_id+'&activity_type='+activity_type).done(function (resp) {
                                var data = resp.data.list;
                                $('#order_id').text(data[0].order_id);
                                $('#user_id').text(data[0].user_id);
                                $('#activity_type').text(window.LOTTERY_TYPE[data[0].activity_type]);
                                $('#bet_name').text(window.get_bet_name(data[0].activity_type, data[0].detail.bet_type));
                                $('#term').text(data[0].detail.term);
                                $('#number').text(window.replace_bet_letter(data[0].detail.number));
                                $('#price').text(data[0].detail.price);
                                $('#win_price').text(data[0].detail.win_price);
                                $('#bonus').text(data[0].detail.bonus);
                                $('#orderStatus').text(window.ORDER_STATUS[data[0].status]);
                                $('#created_at').text(data[0].detail.created_at);
                                $('#updated_at').text(data[0].detail.updated_at);
                            }).fail(function (data) {
                                notify.notifyResp(data);
                            });
                        }else{
                            $.get('/admin/casino_records/?id='+order_id+'&game='+game).done(function (resp) {
                                var data = resp.data.list;
                                $('#order_id').text(data[0].id);
                                $('#user_id').text(data[0].user_id);
                                $('#activity_type').text(window.GAME_TYPE[data[0].type]);
                                if(101 == data[0].type){
                                   $('#bet_name').text(window.BULL_INDEX[data[0].bet_index]);
                                   $('#term').text(data[0].term_number);
                                }else if(103 == data[0].type){
                                   $('#bet_name').text(window.FRUIT_INDEX[data[0].bet_index]);
                                   $('#term').text(data[0].term_number);
                                }else if(104 == data[0].type){
                                   $('#bet_name').text(window.LOTTERY_INDEX[data[0].bet_index]);
                                   $('#term').text(data[0].term_number);
                                }
                                $('#price').text(data[0].bet_amount);
                                $('#win_price').text(data[0].award_amount);
                                $('#created_at').text(data[0].created_at);
                                $('#updated_at').text(data[0].updated_at);
                            }).fail(function (data) {
                                notify.notifyResp(data);
                            });
                        }

                        $('#submitClose').off('click').click(function() {
                            $.magnificPopup.close();
                        });

                    },
                }
            });
            utils.getPaginator(that.options, this.collection.total, '#op/transaction/');

            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/Transaction.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 20;
            var view = new GameOrderListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
});